import React, { useState } from 'react';
import { Button, Form, Input, Select, Card, Space } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { useStore } from '@/store/useStore';

const fieldTypes = [
  { label: '文本', value: 'string' },
  { label: '数字', value: 'number' },
  { label: '布尔值', value: 'boolean' },
  { label: '日期', value: 'date' },
];

const ModelEditor = () => {
  const { models, addModel, updateModel, removeModel } = useStore();
  const [currentModel, setCurrentModel] = useState<string | null>(null);
  const [form] = Form.useForm();
  
  const handleCreateModel = () => {
    const modelName = `model_${Date.now()}`;
    const newModel = {
      name: modelName,
      fields: [{ name: 'id', type: 'string', label: 'ID', required: true }]
    };
    
    addModel(newModel);
    setCurrentModel(modelName);
    form.setFieldsValue(newModel);
  };
  
  const handleSaveModel = () => {
    if (!currentModel) return;
    
    form.validateFields().then(values => {
      updateModel(currentModel, values.fields);
    });
  };
  
  const handleDeleteModel = (modelName: string) => {
    removeModel(modelName);
    if (currentModel === modelName) {
      setCurrentModel(null);
      form.resetFields();
    }
  };
  
  const modelList = Object.values(models);

  return (
    <Card title="数据模型" bordered={false} style={{ height: '100%' }}>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={handleCreateModel} block>
          新建模型
        </Button>
      </div>
      
      <div style={{ marginBottom: 24 }}>
        {modelList.map(model => (
          <Card 
            key={model.name} 
            size="small" 
            style={{ 
              marginBottom: 8,
              borderLeft: currentModel === model.name ? '3px solid #1890ff' : undefined
            }}
            onClick={() => {
              setCurrentModel(model.name);
              form.setFieldsValue(model);
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>{model.name}</div>
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                onClick={(e) => {
                  e.stopPropagation();
                  handleDeleteModel(model.name);
                }}
              />
            </div>
          </Card>
        ))}
      </div>
      
      {currentModel && (
        <Form form={form} layout="vertical">
          <Form.List name="fields">
            {(fields, { add, remove }) => (
              <div>
                {fields.map(({ key, name, ...restField }) => (
                  <Card 
                    key={key} 
                    size="small" 
                    style={{ marginBottom: 12 }}
                    title={`字段 ${name + 1}`}
                    extra={<Button type="text" icon={<DeleteOutlined />} onClick={() => remove(name)} />}
                  >
                    <Space>
                      <Form.Item
                        {...restField}
                        name={[name, 'name']}
                        label="字段名"
                        rules={[{ required: true, message: '请输入字段名' }]}
                      >
                        <Input placeholder="字段名" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'label']}
                        label="显示名称"
                        rules={[{ required: true, message: '请输入显示名称' }]}
                      >
                        <Input placeholder="显示名称" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'type']}
                        label="类型"
                        rules={[{ required: true, message: '请选择类型' }]}
                      >
                        <Select options={fieldTypes} style={{ width: 100 }} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'required']}
                        label="必填"
                        valuePropName="checked"
                      >
                        <Switch />
                      </Form.Item>
                    </Space>
                  </Card>
                ))}
                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                  添加字段
                </Button>
              </div>
            )}
          </Form.List>
          
          <div style={{ marginTop: 16 }}>
            <Button type="primary" onClick={handleSaveModel} block>
              保存模型
            </Button>
          </div>
        </Form>
      )}
    </Card>
  );
};

export default ModelEditor;